<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
	</head>

	<body style="background-color: white;">
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<button id="send" class="mui-pull-right"
				style="background-color: #2AC845; color: white; height: 30px; font-size: 16px; line-height: 30px; padding: 0 12px; margin-top: 7px; border: none;">发表</button>
		</header>
		<div class="mui-content" style="margin: 0 15px 0 20px; background-color: white;">
			<textarea id="says" rows="3" cols="" style="border: 0;" placeholder="这一刻的想法..."></textarea>
			<div id="img-container">

			</div>
		</div>
		<script src="js/mui.js"></script>
		<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/uploader.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			mui.init();
			var self = null;

			var cw = document.documentElement.clientWidth;
			var img_size = (cw - 50) / 3;

			var ele_img_container = document.getElementById('img-container');
			var ele_send = document.getElementById('send');
			var ele_says = document.getElementById('says');
			mui.plusReady(function() {
				self = plus.webview.currentWebview();
				for (let file of self.files.files) {
					var htmlContent = '<img src="' + file + '" width="' + img_size + '" height="' + img_size +
						'" style="object-fit: cover; margin-right: 5px;">';
					ele_img_container.insertAdjacentHTML('afterbegin', htmlContent);
				}
			});

			ele_send.addEventListener('tap', function() {
				let mediaPaths = '';
				for (let file of self.files.files) {
					var name = file.substring(file.lastIndexOf('/') + 1, file.length);
					mediaPaths += app.imageServerAddress + name + ',';
					upload(file);
				}
				
				var friendCircle = {
					userId: app.getGlobalUserInfo().id,
					says: ele_says.value,
					mediaPaths: mediaPaths
				};
				
				fetch(app.serverAddress + '/friendCircle/send', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
					},
					body: JSON.stringify(friendCircle)
				}).then(response => {
					console.log('succeed!');
				}).catch(err => {
					console.log(err);
				});
			});

			function upload(file) {
				var name = file.substring(file.lastIndexOf('/') + 1, file.length);
				uploader.upload(name, url => {
					var img = new Image();
					img.src = file;
					img.onload = () => {
						var canvas = document.createElement('canvas');
						canvas.width = img.width;
						canvas.height = img.height;
						var ctx = canvas.getContext('2d');
						ctx.drawImage(img, 0, 0, img.width, img.height);
						canvas.toBlob(blob => uploader.put(url, blob), 'image/jpg');
					};
				});
			}
		</script>
	</body>
</html>
